package cn.amossun.starter.api.data.security.config;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.json.JsonReadFeature;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import cn.amossun.starter.api.data.security.aspect.DataSecurityAspect;
import cn.amossun.starter.api.data.security.rewrite.DecryptObjectRewriter;
import cn.amossun.starter.api.data.security.rewrite.EncryptObjectRewriter;
import cn.amossun.starter.api.data.security.rule.ApiDecryptRule;
import cn.amossun.starter.api.data.security.rule.ApiEncryptRule;
import cn.amossun.starter.common.constant.Constant;
import cn.amossun.starter.common.util.DateTimeUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.lang.reflect.Field;
import java.security.Security;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZoneId;
import java.util.Collection;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

@ConditionalOnProperty(
        prefix = Constant.AMOS_SUN_DATA_SECURITY,
        name = "api.enabled",
        havingValue = "true"
)
@AllArgsConstructor
@EnableConfigurationProperties(ApiDataSecurityConfig.class)
@Configuration
@Slf4j
public class ApiDataSecurityConfigure {

    /** official bean**/

    /*@Bean
    @ConditionalOnMissingBean(JSONConfig.class)
    @ConditionalOnClass(ApiDataSecurityConfig.class)
    JSONConfig htJsonConfig(ApiDataSecurityConfig apiDataSecurityConfig){
        JSONConfig htJsonConfig = new JSONConfig();
        htJsonConfig.setDateFormat(apiDataSecurityConfig.getApi().getPatternDatetime());
        htJsonConfig.setIgnoreNullValue(false);
        return htJsonConfig;
    }*/

    @Bean("amosObjectMapper")
    @ConditionalOnMissingBean(name = "amosObjectMapper")
    @ConditionalOnClass(ApiDataSecurityConfig.class)
    ObjectMapper htJsonConfig(ApiDataSecurityConfig apiDataSecurityConfig){
        ObjectMapper objectMapper = new ObjectMapper();
        //设置地点为中国
        objectMapper.setLocale(Locale.CHINA);
        //去掉默认的时间戳格式
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        //设置为中国上海时区
        objectMapper.setTimeZone(TimeZone.getTimeZone(ZoneId.systemDefault()));
        //序列化时，日期的统一格式
        objectMapper.setDateFormat(new SimpleDateFormat(apiDataSecurityConfig.getApi().getPatternDatetime(), Locale.CHINA));
        //序列化处理
        objectMapper.configure(JsonReadFeature.ALLOW_UNESCAPED_CONTROL_CHARS.mappedFeature(), true);
        objectMapper.configure(JsonReadFeature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER.mappedFeature(), true);
        //失败处理
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //单引号处理
        objectMapper.configure(JsonReadFeature.ALLOW_SINGLE_QUOTES.mappedFeature(), true);
        //反序列化时，属性不存在的兼容处理
        objectMapper.getDeserializationConfig().withoutFeatures(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
        //日期格式化
        objectMapper.registerModule(build());
        objectMapper.findAndRegisterModules();
        setNullValueSerializer(objectMapper);

        return objectMapper;
    }

    public JavaTimeModule build(){
        JavaTimeModule javaTimeModule = new JavaTimeModule();
        javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeUtil.DATETIME_FORMAT));
        javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeUtil.DATE_FORMAT));
        javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeUtil.TIME_FORMAT));
        javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeUtil.DATETIME_FORMAT));
        javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeUtil.DATE_FORMAT));
        javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeUtil.TIME_FORMAT));
        return javaTimeModule;
    }

    protected void setNullValueSerializer(ObjectMapper objectMapper) {
        objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {
            @Override
            public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
                String fieldName = jsonGenerator.getOutputContext().getCurrentName();
                try {
                    //反射获取字段类型
                    Field field = jsonGenerator.getCurrentValue().getClass().getDeclaredField(fieldName);
                    if (CharSequence.class.isAssignableFrom(field.getType())) {
                        //字符串型空值""
                        jsonGenerator.writeString(StrUtil.EMPTY);
                        return;
                    } else if (Collection.class.isAssignableFrom(field.getType())) {
                        //列表型空值返回[]
                        jsonGenerator.writeStartArray();
                        jsonGenerator.writeEndArray();
                        return;
                    } else if (Map.class.isAssignableFrom(field.getType())) {
                        //map型空值 或者 bean对象 返回{}
                        jsonGenerator.writeStartObject();
                        jsonGenerator.writeEndObject();
                        return;
                    }
                } catch (NoSuchFieldException ignored) {
                }

                jsonGenerator.writeString(StrUtil.EMPTY);
            }
        });
    }


    @Bean
    @ConditionalOnMissingBean(BouncyCastleProvider.class)
    public BouncyCastleProvider addBouncyCastleProvider(){
        BouncyCastleProvider bouncyCastleProvider = new BouncyCastleProvider();
        Security.addProvider(bouncyCastleProvider);
        return bouncyCastleProvider;
    }


    /** custom bean **/
    @Bean
    @ConditionalOnClass(ApiDataSecurityConfig.class)
    public ApiDecryptRule apiDecryptRule(BouncyCastleProvider bouncyCastleProvider, ApiDataSecurityConfig apiDataSecurityConfig) throws Exception {
        return new ApiDecryptRule(apiDataSecurityConfig);
    }

    @Bean
    @ConditionalOnClass(ApiDecryptRule.class)
    public DecryptObjectRewriter decryptObjectRewriter(ApiDecryptRule apiDecryptRule) {
        return new DecryptObjectRewriter(apiDecryptRule);
    }

    @Bean
    @ConditionalOnClass(ApiDataSecurityConfig.class)
    public ApiEncryptRule apiEncryptRule(BouncyCastleProvider bouncyCastleProvider, ApiDataSecurityConfig apiDataSecurityConfig) throws Exception {
        return new ApiEncryptRule(apiDataSecurityConfig);
    }

    @Bean
    @ConditionalOnBean(value = {ApiEncryptRule.class,ObjectMapper.class})
    public EncryptObjectRewriter encryptObjectRewriter(ApiEncryptRule apiEncryptRule,
                                                       @Qualifier("amosObjectMapper") ObjectMapper objectMapper) {
        return new EncryptObjectRewriter(apiEncryptRule, objectMapper);
    }

    @Bean
    @ConditionalOnClass(DecryptObjectRewriter.class)
    DataSecurityAspect dataSecurityAspect(DecryptObjectRewriter decryptObjectRewriter) {
        return new DataSecurityAspect(decryptObjectRewriter);
    }

}
